var directionDisplay;
var map;
var geocoder;
var distance = 0;
var markerArray = [];
var infowindow;
var directionsService = new google.maps.DirectionsService();
function lokalizuj(){
	var adres = document.getElementById('adres').value;
	adres= adres.replace('ó', 'o');
	adres= adres.replace('ą', 'a');
	adres= adres.replace('ę', 'e');
	adres= adres.replace('ś', 's');
	adres= adres.replace('ć', 'c');
	adres= adres.replace('ż', 'z');
	adres= adres.replace('ź', 'z');
	adres= adres.replace('ń', 'n');
	adres= adres.replace('ł', 'l');
	xmlhttp=new XMLHttpRequest();
	xmlhttp.open("GET","mapa?adres="+adres,true);
	xmlhttp.send();
	xmlhttp.onreadystatechange=function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
				var a = xmlhttp.responseText;

				codeAddress(a);

		}			
	};
}

function initialize() {
  geocoder = new google.maps.Geocoder();
  directionDisplay = new google.maps.DirectionsRenderer({suppressMarkers: true});
  var krakow = new google.maps.LatLng(52.040900, 19.285000);
  var myOptions = {
    zoom: 7,
    maxZoom: 20,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: krakow
  };
  map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  var southWest = new google.maps.LatLng(49.000000,14.070000);
  var northEast = new google.maps.LatLng(54.500000,24.080000);
  var bounds = new google.maps.LatLngBounds(southWest,northEast);
  map.fitBounds(bounds);
  directionDisplay.setMap(map);
  infowindow = new google.maps.InfoWindow({
	  content: 'behold...'
	});
}

function codeAddress(adres) {
	deleteOverlays();
	var b = adres.split(';');
	for(var i=0;i<b.length-1;i++){
		var c = b[i].split('|');
		var address= c[0];
		var telefon= c[1];
		var nazwa= c[2];
		var location = new google.maps.LatLng(c[3], c[4]);

        if(b.length==2){
        map.setZoom(15);
        }
        else{
        	map.setZoom(11);
        }
        addMarker(location, address, nazwa, telefon);
        map.setCenter(location);
     
	}
  }
function addMarker(location, adres, nazwa, telefon) {
	
	  marker = new google.maps.Marker({
	    position: location,
	    map: map,
	    title: adres
	  });
	  markerArray.push(marker);
	  google.maps.event.addListener(marker, 'click', function() {
		  infowindow.setContent('<div class=content><b>'+nazwa+'</b><br>'+adres+'<br>'+telefon+'</div>');
		  infowindow.open(map,this);
		});
	}
function deleteOverlays() {
	  if (markerArray) {
	    for (i in markerArray) {
	      markerArray[i].setMap(null);
	    }
	    markerArray.length = 0;
	  }
	}

function rysujDroge(start,waypts, idkuriera){
	var request = {
		    origin:start,
		    destination:start,
		    waypoints: waypts,
		    optimizeWaypoints: true,
		    travelMode: google.maps.TravelMode.DRIVING
		  };
	var nadtekst="";
	var czas=0;
		  directionsService.route(request, function(result, status) {
		    if (status == google.maps.DirectionsStatus.OK) {
		      var route = result.routes[0];
		      for (var i = 0; i < route.legs.length; i++) {
		    	czas += route.legs[i].duration.value;
		    	nadtekst+=route.legs[i].start_location+";"+route.legs[i].start_address+";"+czas+"|";  
		      }
		      var xmlhttp = new getXMLObject();
		 	 if(xmlhttp) { 
		 		    xmlhttp.open("GET","trasa2?idkuriera="+idkuriera+"&tekst="+nadtekst,false); //false = synchronicznie		    
		 		    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		 		    xmlhttp.send(null); // czeka na odpo. 
		 		  }	
		 	 var mapa = xmlhttp.responseText;
		      
		      
		    }
		  });
	
}
function rysujDroge2(start,waypts){
	var request = {
		    origin:start,
		    destination:start,
		    waypoints: waypts,
		    optimizeWaypoints: false,
		    travelMode: google.maps.TravelMode.DRIVING
		  };
		  directionsService.route(request, function(result, status) {
		    if (status == google.maps.DirectionsStatus.OK) {
		      directionDisplay.setDirections(result);
		      var route = result.routes[0];
		      for (var i = 0; i < route.legs.length; i++) {
		    	if(i==0){
		    		makeMarker(route.legs[i].start_location,route.legs[i].start_address,"images/marker1.gif",false);
		    	}
		    	else{
		    		makeMarker(route.legs[i].start_location,route.legs[i].start_address,"images/marker"+(i+1)+".gif",true);
		    	}
		      }    
		    }
		  });
	
}
function getXMLObject()  //XML OBJECT
{
   var xmlHttp = false;
   try {
     xmlHttp = new ActiveXObject("Msxml2.XMLHTTP")  // For Old Microsoft Browsers
   }
   catch (e) {
     try {
       xmlHttp = new ActiveXObject("Microsoft.XMLHTTP")  // For Microsoft IE 6.0+
     }
     catch (e2) {
       xmlHttp = false ;  // No Browser accepts the XMLHTTP Object then false
     }
   }
   if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
     xmlHttp = new XMLHttpRequest();        //For Mozilla, Opera Browsers
   }
   return xmlHttp;  // Mandatory Statement returning the ajax object created
}
function wyswietlKurierow(){
	setInterval("wyswietlKurierow2()", 5000);	
}

function wyswietlKurierow2(){
	clearOverlays();
	var xmlhttp = new getXMLObject();
	 if(xmlhttp) { 
		    xmlhttp.open("GET","pozycja",false); //false = synchronicznie		    
		    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		    xmlhttp.send(null); // czeka na odpo. 
		  }	
	 var mapa = xmlhttp.responseText;
	 var mapa2 = mapa.split("|");
	 for(var i=0;i<mapa2.length;i++){
		 var mapa3=mapa2[i].split(",");
		 var data1 = new Date(mapa3[4]);
		 var data2 = new Date(mapa3[5]);
		 var roznica = data2.getTime()-data1.getTime();
		 
		 var milliseconds = roznica;
		 var seconds = parseInt(milliseconds / 1000);
		 var minutes = parseInt(seconds / 60);
		 seconds %= 60;
		 var hours = parseInt(minutes / 60);
		 minutes %= 60;
		 var days = parseInt(hours / 24);
		 hours %= 24;
		 
		 makeMarker2(new google.maps.LatLng(mapa3[0], mapa3[1]),"<b>"+mapa3[2]+" "+mapa3[3]+"</b><br>Czas od ostatniej aktualizacji:<br>" +
		 		days+" dni "+hours+"h "+minutes+"m "+seconds+"s","images/marker1.gif");

	 }
}

function clearOverlays() {
	  if (markerArray) {
	    for (i in markerArray) {
	      markerArray[i].setMap(null);
	    }
	  }
	}


function makeMarker( position, title,img,czy) {
	var marker = new google.maps.Marker({
	  position: position,
	  map: map,
	  icon: img,
	  title: title
	 });
	var tresc = "";
	if(czy)
		tresc = '<div class=content><b>'+title+'</b><br><a href="zamowienie.jsp?adres='+title+'">Strona zamowienia</a></div>';
		else
			tresc = '<div class=content><b>'+title+'</b></div>';
	markerArray.push(marker);
	 google.maps.event.addListener(marker, 'click', function() {
		  infowindow.setContent(tresc);
		  infowindow.open(map,this);
		});
	}
function makeMarker2( position, title,img ) {
	var marker = new google.maps.Marker({
	  position: position,
	  map: map,
	  icon: img,
	  title: title
	 });
	markerArray.push(marker);
	 google.maps.event.addListener(marker, 'click', function() {
		  infowindow.setContent('<div class=content>'+title+'</div>');
		  infowindow.open(map,this);
		});
	}